package com.example.sunran.auth;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.Map;

@TokenNeeded
@Priority(Priorities.AUTHENTICATION)
public class TokenNeededFilter implements ContainerRequestFilter {
    @Override
    public void filter(ContainerRequestContext containerRequestContext) throws IOException {

        String headerString = containerRequestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        if(headerString==null){
            Map<String, Cookie> map  = containerRequestContext.getCookies();
            if (map.get("sid") != null) {
                headerString = new String(Base64.decodeBase64(map.get("sid").getValue().getBytes()));
            }
        }

        if(StringUtils.isBlank(headerString)){
            containerRequestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
            return;
        }

        String token = headerString.substring("Bearer".length()).trim();


        try {
            String id = TokenCodeUtils.parse(token);
            containerRequestContext.getHeaders().add("sid",id);
        } catch (Exception e) {
            e.printStackTrace();
            containerRequestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
        }
    }
}
